# -*- coding: utf-8 -*-
# @Time    : 2024/7/30 16:33
# @Author  : yujiahao
# @File    : 69_fastapi_websocket_depen.py
# @description: 带依赖的 websocket

"""
使用 Depends 和其他依赖项
在 WebSocket 端点中，您可以从 fastapi 导入并使用以下内容：

- Depends
- Security
- Cookie
- Header
- Path
- Query

它们的工作方式与其他 FastAPI 端点/路径操作相同。
"""

from typing import Annotated

from fastapi import (
    Cookie,
    Depends,
    FastAPI,
    Query,
    WebSocket,
    WebSocketException,
    status,
)
from fastapi.responses import HTMLResponse

# 创建 FastAPI 应用实例
app = FastAPI()

# 定义 HTML 页面内容
html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
            <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
            <button onclick="connect(event)">Connect</button>
            <hr>
            <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
        var ws = null;
            function connect(event) {
                var itemId = document.getElementById("itemId")
                var token = document.getElementById("token")
                ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
                ws.onmessage = function(event) {
                    var messages = document.getElementById('messages')
                    var message = document.createElement('li')
                    var content = document.createTextNode(event.data)
                    message.appendChild(content)
                    messages.appendChild(message)
                };
                event.preventDefault()
            }
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""


# 定义一个 GET 路由，返回 HTML 页面
@app.get("/")
async def get():
    return HTMLResponse(html)


# 依赖项函数，用于从 Cookie 或 Query 参数中获取 session 或 token
async def get_cookie_or_token(
        websocket: WebSocket,
        session: Annotated[str | None, Cookie()] = None,
        token: Annotated[str | None, Query()] = None,
):
    # 如果 session 和 token 都不存在，抛出 WebSocketException
    if session is None and token is None:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    # 返回 session 或 token 的值
    return session or token


# WebSocket 端点，处理 WebSocket 连接
@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
        *,
        websocket: WebSocket,
        item_id: str,
        q: int | None = None,
        cookie_or_token: Annotated[str, Depends(get_cookie_or_token)],
):
    # 接受 WebSocket 连接
    await websocket.accept()
    while True:
        # 接收客户端发送的消息
        data = await websocket.receive_text()
        # 发送 session 或 token 的值给客户端
        await websocket.send_text(
            f"Session cookie or query token value is: {cookie_or_token}"
        )
        # 如果查询参数 q 存在，发送其值给客户端
        if q is not None:
            await websocket.send_text(f"Query parameter q is: {q}")
        # 发送接收到的消息和 item_id 给客户端
        await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
